package com.devgroupvn.dota.hero;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.view.View;
import android.view.View.OnClickListener;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ImageView;
import android.widget.ScrollView;
import android.widget.TextView;

import com.devgroupvn.dota.Application;
import com.devgroupvn.dota.R;
import com.devgroupvn.dota.data.GetHero;
import com.devgroupvn.dota.data.Hero;
import com.google.ads.AdRequest;
import com.google.ads.AdView;
import com.kin.bitmapcatching.DisplayBitmap.ObserveCatching;
import com.kin.bitmapcatching.ImageDownloader;
import com.kin.bitmapcatching.ImageDownloader.AsyncDownloadDrawable;
import com.kin.bitmapcatching.ImageDownloader.BitmapDownloaderTask;

public class HeroDetail extends Activity implements OnClickListener, ObserveCatching
{
	String mLink;
	Hero entryHero;
	GetHero getHero;
	WebView mWebView;
	ImageView avt;
	TextView tvName;
	TextView tvStrength;
	TextView tvSpec;
	TextView tvDescription;
	TextView tvAbilities;
	ScrollView scrollview;
	AdView adView;
	private static ProgressDialog progressDialog;
	int select = 0;
	
	@Override
	protected void onCreate(Bundle savedInstanceState)
	{
		super.onCreate(savedInstanceState);
		setContentView(R.layout.herodetail_layout);

		getHero = new GetHero();
		entryHero = (Hero) Application.getInstance().getData("entryhero");
		
		init();
		configWebview();
		new AsynGetDetalHero().execute();
	}

	private void configWebview()
	{
		mWebView.setWebChromeClient(new WebChrome());
		mWebView.setWebViewClient(new Webclient());

//		mWebView.getSettings().setJavaScriptEnabled(true);
//		mWebView.getSettings().setBuiltInZoomControls(true);
		mWebView.setHorizontalScrollBarEnabled(true);
		mWebView.getSettings().setCacheMode(WebSettings.LOAD_CACHE_ELSE_NETWORK);
		mWebView.setVerticalScrollbarOverlay(true);
	}

	private class AsynGetDetalHero extends AsyncTask<Void, Void, Void>
	{

		@Override
		protected void onPreExecute()
		{
			super.onPreExecute();
			progressDialog = ProgressDialog.show(HeroDetail.this, null, "Waiting..", true, false);
		}

		@Override
		protected Void doInBackground(Void... params)
		{
			if (isNetworkAvailable())
			{
			
				getHero.getHeroDetail(entryHero);
			}
			return null;
		}

		@Override
		protected void onPostExecute(Void result)
		{
			setInit();
			progressDialog.dismiss();
			super.onPostExecute(result);
		}

	}

	private void init()
	{
		mWebView = (WebView) findViewById(R.id.webview);
		avt = (ImageView) findViewById(R.id.iv_detailHero_avt);
		tvName = (TextView) findViewById(R.id.tv_detailHero_name);
		tvStrength = (TextView) findViewById(R.id.tv_detailHero_strength);
		tvSpec = (TextView) findViewById(R.id.tv_detailHero_spec);
		tvDescription = (TextView) findViewById(R.id.tv_detailHero_des);
		tvAbilities = (TextView) findViewById(R.id.tv_detailHero_abilities);
		adView = (AdView) findViewById(R.id.adView);
		scrollview = (ScrollView)findViewById(R.id.scrollview);
		setupAdwhirl();
		tvName.setText(entryHero.name);
		loadBitmapWithMemCache(entryHero.image, avt);

	}

	private void setInit()
	{
		tvAbilities.setOnClickListener(this);
		tvSpec.setOnClickListener(this);
		tvStrength.setOnClickListener(this);
		tvDescription.setOnClickListener(this);

		loadBitmapWithMemCache(entryHero.image, avt);
		tvDescription.setText(entryHero.description);
		if (select != 0)
		{
			switch (select)
			{
			case 1:
				if (!entryHero.info.equals("") || entryHero.info != null)
				{
					LoadWeb(entryHero.info);
					mWebView.setVisibility(View.VISIBLE);
				}
				break;
			case 2:
				if (!entryHero.abilities.equals("") || entryHero.abilities != null)
				{
					LoadWeb(entryHero.abilities);
					mWebView.setVisibility(View.VISIBLE);
				}
				break;
			case 3:
				if (!entryHero.spec.equals("") || entryHero.spec != null)
				{
					LoadWeb(entryHero.spec);
					mWebView.setVisibility(View.VISIBLE);
				}
				break;
			default:
				break;
			}
		}
	}

	private void LoadWeb(String str)
	{
		mWebView.loadData(str, "text/html", "utf-8");
	}

	private void setupAdwhirl()
	{
		try
		{
			final Handler handle = new Handler();
			final Runnable run = new Runnable()
			{

				@Override
				public void run()
				{
					AdRequest request = new AdRequest();
					adView.loadAd(request);
					handle.postDelayed(this, 5000);

				}
			};
			handle.postDelayed(run, 5000);
		}
		catch (Exception e)
		{

		}
	}

	private boolean isNetworkAvailable()
	{

		ConnectivityManager connMgr = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
		NetworkInfo info = connMgr.getActiveNetworkInfo();
		return (info != null && info.isConnected());
	}

	private class Webclient extends WebViewClient
	{
		@Override
		public boolean shouldOverrideUrlLoading(WebView view, String url)
		{

			view.loadUrl(url);

			return true;
		}
	}

	private class WebChrome extends WebChromeClient
	{

		@Override
		public void onProgressChanged(WebView view, int newProgress)
		{
			super.onProgressChanged(view, newProgress);
			{
				if (newProgress < 100)
				{
					/*
					 * pb.setVisibility(View.VISIBLE);
					 * tvLoading.setVisibility(View.VISIBLE); tvLoading
					 * .setText(newProgress + "%");
					 */
				}
				/*
				 * pb.setProgress(newProgress); if(newProgress == 100) {
				 * pb.setVisibility(ProgressBar.GONE);
				 * tvLoading.setVisibility(View.GONE); }
				 */
			}
		}

	}

	@Override
	public void onClick(View v)
	{
		switch (v.getId())
		{
		case R.id.tv_detailHero_strength:
			if (entryHero.info == null||entryHero.info.equals(""))
			{
				select = 1;
				new AsynGetDetalHero().execute();
			}
			else
			{
				LoadWeb(entryHero.info);
				mWebView.setVisibility(View.VISIBLE);
				scrollview.post(new Runnable() {

			        @Override
			        public void run() {
			        	scrollview.fullScroll(ScrollView.FOCUS_DOWN);
			        }
			    });
			}
			break;
		case R.id.tv_detailHero_abilities:
			if ( entryHero.abilities == null || entryHero.abilities.equals(""))
			{
				select = 2;
				new AsynGetDetalHero().execute();
			}
			else
			{
				LoadWeb(entryHero.abilities);
				mWebView.setVisibility(View.VISIBLE);
				scrollview.post(new Runnable() {

			        @Override
			        public void run() {
			        	scrollview.fullScroll(ScrollView.FOCUS_DOWN);
			        }
			    });
			}
			break;
		case R.id.tv_detailHero_spec:
			if (entryHero.spec == null || entryHero.spec.equals(""))
			{
				select = 3;
				new AsynGetDetalHero().execute();
			}
			else
			{
				LoadWeb(entryHero.spec);
				mWebView.setVisibility(View.VISIBLE);
				scrollview.post(new Runnable() {

			        @Override
			        public void run() {
			        	scrollview.fullScroll(ScrollView.FOCUS_DOWN);
			        }
			    });
			}
			break;
		default:
			break;
		}
	}

	@Override
	public void addBitmapToMemCache(String key, Bitmap bitmap)
	{
		if (getBitmapFromMemCache(key) == null)
		{
			if (bitmap != null)
			{
				Application.mMemCache.put(key, bitmap);
			}
		}

		if (!Application.mDiskCache.containsKey(key))
		{
			Application.mDiskCache.put(key, bitmap);
		}
	}

	@Override
	public Bitmap getBitmapFromMemCache(String key)
	{
		return Application.mMemCache.get(key);
	}

	@Override
	public Bitmap getBitmapFromDiskCache(String key)
	{
		return Application.mMemCache.get(key);
	}

	private void loadBitmapWithMemCache(String fileName, ImageView imageView)
	{
		if (ImageDownloader.cancelPotentialWork(fileName, imageView))
		{
			final String imageKey = String.valueOf(fileName);
			final Bitmap bitmap = getBitmapFromMemCache(imageKey);
			if (bitmap == null)
			{
				ImageDownloader imageDownloader = new ImageDownloader(this, this);
				final BitmapDownloaderTask task = imageDownloader.new BitmapDownloaderTask(imageView, this);
				Bitmap temp = BitmapFactory.decodeResource(this.getResources(), R.drawable.icon);
				final AsyncDownloadDrawable asyncDrawable = new AsyncDownloadDrawable(this.getResources(), temp, task);
				imageView.setImageDrawable(asyncDrawable);
				task.execute(fileName);
			}
			else
			{
				imageView.setImageBitmap(bitmap);
			}
		}
	}
}
